# _*_ coding:utf-8 _*_
# @Time  : 2022.10.11
# @Author: zizlee
import datetime
import json
import time
import pandas as pd

import requests
from urllib3 import disable_warnings
disable_warnings()

HOST = 'https://210.13.218.130:9000/'


# def get_date_rng(start, end):  # 获取起始日期到结束日期的每月的最后一天
#     start_date = datetime.datetime.strptime(start, '%Y%m%d').date()
#     end_date = datetime.datetime.strptime(end, '%Y%m%d').date()
#     return [m.strftime('%Y%m%d') for m in pd.date_range(start_date, end_date, freq='M')]


def print_progress_bar(current, total, color=35, title=''):  # percent是小数
    percent = round(current/total, 4)
    prefix_progress = '▓' * int(80 * percent)
    leave_progress = '▓' * (80 - int(80 * percent))
    # percent = '%.2f' % (percent * 100)
    print(f'\033[1;{color}m{current}/{total}\033[0m|\033[1;{color}m{prefix_progress}\033[0m{leave_progress} {title}')


def read_indexes(pointers=None):
    with open('R_品种交割数据.json', encoding='utf8', mode='r') as fp:
        indexes = json.load(fp)
    if pointers:
        indexes = list(filter(lambda x: x['source_id'] in pointers, indexes))
    print('读取本地数量:', len(indexes))

    # 读取网络指标数据，过滤并修改起始日期
    r = requests.get(HOST + 'v1/datalib/table/indexGroups/', verify=False)
    customer_indexes = None
    for g in r.json()['data']:
        if g['group'] == 'rj1':
            customer_indexes = g['data']
    # print('读取网络指标数量:', len(customer_indexes))

    local_indexes = {i['source_id']: i for i in indexes}
    customer_indexes = list(filter(lambda x: x['source_id'] in local_indexes.keys(), customer_indexes))
    for ci in customer_indexes:
        local_item = local_indexes.get(ci['source_id'])
        if not local_item:
            raise ValueError(f'{ci["name_zh"]}数据项不存在！')
        for k, v in local_item.items():
            if k not in ci.keys():
                ci[k] = v
    print('待更新指标数量:', len(customer_indexes))
    return customer_indexes


def get_index_values(index_item):
    start_date = index_item['enddate'] if index_item['enddate'] else index_item['startdate']
    start_date = start_date.replace('-', '')
    url = HOST + 'v1/exchange/delivery/?start={}&end={}&v={}'.format(start_date, CLOSE_DATE, index_item['variety_en'])
    r = requests.get(url, verify=False)
    delivery_data = r.json()['data']
    # print(delivery_data)
    df = pd.DataFrame(delivery_data)
    # 处理date
    df['delivery_date'] = df['delivery_date'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d').strftime('%Y-%m-%d'))
    df.rename(columns={'delivery_date': 'datadate', index_item['value_key']: 'datavalue'}, inplace=True)
    df.sort_values(by='datadate', inplace=True)
    return df[['datadate', 'datavalue']].to_dict(orient='records')


def save_index(sheet_id, datalist):
    url = HOST + 'v1/datalib/table/update/'
    body_data = {
        'dataid': sheet_id,
        'row_value': datalist
    }
    try:
        r = requests.post(url, json=body_data, verify=False)
        if r.json()['code'] != 200:
            raise ValueError(f'status_code={r.json()["code"]}')
    except Exception as e:
        if datalist:
            msg = f'保存数据指标 ID={sheet_id}失败了：{e}'
        else:
            msg = f'更新指标 ID={sheet_id} 刷新日期失败了：{e}'
        print(msg)
        return False
    else:
        return True


if __name__ == '__main__':
    CLOSE_DATE = '20231130'
    index_list = read_indexes()
    # index_list = list(filter(lambda x: x['source_id'] in ['R00021484', 'R00021485'], index_list))

    total_count = len(index_list)
    for c_index, item in enumerate(index_list):
        values = get_index_values(item)
        if len(values) <= 1:
            print(f'{item["name_zh"]},指标{item["source_id"]},无新数据.')
            continue
        success = save_index(item['id'], values)
        if success:
            s_date = item['enddate'] if item['enddate'] else item['startdate']
            message = f'{item["name_zh"]},指标{item["source_id"]},起始日期:{s_date}保存完成.'
            color = 35
        else:
            message = f'{item["name_zh"]},指标{item["source_id"]},保存失败!'
            color = 31
        print_progress_bar(current=c_index + 1, color=color, total=total_count, title=message)
        time.sleep(1)
